from django.core.management.base import BaseCommand, CommandError
from connie2_django.connie2.models import ConnieRun
from connie2_django.connie2.connieparser import run_parse
from connie2_django.connie2.plotter import plot_results
import os.path as op

class Command(BaseCommand):
    help = "Parse and plot the results (both final and all-time) for the runid/results file combo specified on the command line."
    args = "<runid> <results file>"

    def handle(self, *args, **options):
        if len(args) != 2:
            raise CommandError, "Must specify exactly two arguments; the run id and the results file."
        runid, filename = args
        try:
            runid = int(runid)
        except:
            raise CommandError, "Run id (%s) must be an integer" % runid
        if not op.exists(filename):
            raise CommandError, "File %s doesn't exist" % filename

        # work out the base for the plots:
        basefile = op.basename(filename)
        i = basefile.rfind('.')
        filebasename = basefile[:i] if i >= 0 else basefile

        allstatsname = filebasename + '-all.png'
        finalstatsname = filebasename + '-final.png'

        # retrieve the run configuration (needed to plot the initial positions on the plot):
        try:
            run = ConnieRun.objects.get(id=runid)
        except:
            raise CommandError, "Run id %d can't be found." % runid

        # open and parse the results file:
        inputfile = open(filename, 'r')
        try:
            results = run_parse(inputfile)
        except:
            raise CommandError, "There was an error parsing the results file %s" % inputfile
        finally:
            inputfile.close()

        try:
            f = open(allstatsname, 'wb')
            img = plot_results(results, run, plottype='all', standalone=True)
            f.write(img)
        except:
            import traceback; traceback.print_exc()
            raise CommandError, 'There was an error while attempting to plot the all-time stats'
        finally:
            f.close()

        try:
            f = open(finalstatsname, 'wb')
            img = plot_results(results, run, plottype='final', standalone=True)
            f.write(img)
        except:
            raise CommandError, 'There was an error while attempting to plot the final positions'
        finally:
            f.close()

        
